package com.lishangshan.oas_system.controller.daymanage;

import com.lishangshan.oas_system.model.dao.daymanagedao.DaymanageDao;
import com.lishangshan.oas_system.model.dao.scheduledao.ScheduleDao;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.DeptDao;
import com.lishangshan.oas_system.model.dao.user.PositionDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.schedule.ScheduleList;
import com.lishangshan.oas_system.model.entity.system.SystemStatusList;
import com.lishangshan.oas_system.model.entity.system.SystemTypeList;
import com.lishangshan.oas_system.model.entity.user.Dept;
import com.lishangshan.oas_system.model.entity.user.Position;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

@Controller
@RequestMapping("/")
public class ScheduleListController {
    private int size = ParameterUtil.PAGE_SIZE_MIN;
    private Pageable pa;

    @Autowired
    private UserDao userDao;
    @Autowired
    private DaymanageDao daymanageDao;
    @Autowired
    private ScheduleDao scheduleDao;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private StatusDao statusDao;


    /**
     * 日程管理
     *
     * @param page
     * @param userId
     * @param model
     * @return
     */
    // daymanage
    @RequestMapping("daymanage")
    public String daymanage(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page,
                            @SessionAttribute("userId") Long userId, Model model) {
        String val = "";
//        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "statusId"));
        orders.add(new Sort.Order(Sort.Direction.DESC, "typeId"));
        orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
        Sort sort = new Sort(orders);
        pa = new PageRequest(page, size, sort);
        User u = userDao.findOne(userId);
        System.out.println("User" + u);
        Page<ScheduleList> listPage = daymanageDao.findByUser(u, pa);
        typeAndStatus(model);
        model.addAttribute("page", listPage);
        model.addAttribute("schedules", listPage.getContent());
        model.addAttribute("url", "daymanagepaging");
        model.addAttribute("sort", "&val=" + val);
        return "daymanage/daymanage";
    }

    @RequestMapping("daymanagepaging")
    public String daymanagepaging(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page,
                                  @SessionAttribute("userId") Long userId, Model model, @RequestParam(value = "val", required = false) String val) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "statusId"));
        orders.add(new Sort.Order(Sort.Direction.DESC, "typeId"));
        orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
        Sort sort = new Sort(orders);
        pa = new PageRequest(page, size, sort);
        User u = userDao.findOne(userId);
        Page<ScheduleList> listPage = null;
        if (val == null || "".equals(val)) {
            listPage = daymanageDao.findByUser(u, pa);
        } else {
            listPage = daymanageDao.findByUserAndVal(u, val, pa);
        }
        System.out.println("User" + u);
        System.out.println("listPage = " + listPage.getContent());
        typeAndStatus(model);
        model.addAttribute("page", listPage);
        model.addAttribute("schedules", listPage.getContent());
        model.addAttribute("url", "daymanagepaging");
        model.addAttribute("sort", "&val=" + val);
        return "daymanage/daymanagepaging";
    }

    /**
     * @return
     */
    @RequestMapping("dayedit")
    public String dayedit(@RequestParam(value = "rcid", defaultValue = ParameterUtil.ROLE_DEFLUT) Long rcid, Model model
            , HttpServletRequest req, @SessionAttribute("userId") Long userId) {
        ScheduleList scheduleList = null;
        if (rcid == -1) {
            System.out.println("进入添加");
        } else {
            scheduleList = daymanageDao.findOne(rcid);
        }
        acceptList(0, model, userId);
        typeAndStatus(model);
        model.addAttribute("pageflag", req.getParameter("page"));
        model.addAttribute("rc", scheduleList);

        return "daymanage/editday";
    }

    @Autowired
    private PositionDao positionDao;
    @Autowired
    private DeptDao deptDao;

    /**
     * 数据 初始化
     *
     * @param page
     * @param model
     * @param userId
     */
    private void acceptList(int page, Model model, Long userId) {
        pa = new PageRequest(page, size);
        Page<User> userPage = userDao.findByFatherId(userId, pa);
        deptAndPos(model);
        model.addAttribute("url", "schnames");
        model.addAttribute("page", userPage);
        model.addAttribute("emplist", userPage.getContent());
    }

    /**
     * 上一页下一页
     *
     * @param page
     * @param model
     * @param userId
     * @param baseKey
     * @return
     */
    @RequestMapping("schnames")
    private String schnames(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model,
                            @SessionAttribute("userId") Long userId,
                            @RequestParam(value = "baseKey", required = false) String baseKey) {
        Page<User> userPage = null;
        pa = new PageRequest(page, size);
        if (baseKey == null || "".equals(baseKey)) {
            userPage = userDao.findByFatherId(userId, pa);
        } else {
            userPage = userDao.findbyFatherId(baseKey, userId, pa);
        }
        deptAndPos(model);
        model.addAttribute("url", "schnames");
        model.addAttribute("page", userPage);
        model.addAttribute("emplist", userPage.getContent());
        return "common/recivers";
    }

    /**
     * 新增和修改
     *
     * @param scheduleList
     * @param userId
     * @param model
     * @param req
     * @return
     */
    @RequestMapping("addandchangeday")
    public String addandchangeday(ScheduleList scheduleList, @SessionAttribute("userId") Long userId, Model model, HttpServletRequest req, @RequestParam(value = "shareuser", required = false) String names) {
        List<User> users = new ArrayList<>();
        // 获取接收人根据名称查找用户，迭代保存数据
        StringTokenizer tokenizer = new StringTokenizer(names, ";");
        while (tokenizer.hasMoreElements()) {
            users.add(userDao.findByUserName(tokenizer.nextToken()));
        }
        scheduleList.setUsers(users);
        if (scheduleList.getRcId() == null) {
            System.out.println("进入添加");
            model.addAttribute("success", "添加成功");
        } else {
            System.out.println("进入修改");
            model.addAttribute("success", "修改成功");
        }
        scheduleList.setUser(userDao.findOne(userId));
        daymanageDao.save(scheduleList);
        return "forward:/daymanage?page=" + req.getParameter("pageflag");
    }

    @RequestMapping("dayremove")
    public String dayremove(@RequestParam("rcid") Long rcid, HttpServletRequest req) {
        daymanageDao.delete(rcid);
        req.setAttribute("success", "删除成功");
        return "forward:/daymanage?page=" + req.getParameter("page");
    }

    /**
     * 我的日程初始化
     *
     * @return
     */
    @RequestMapping("daycalendar")
    public String daycalendar() {
        return "daymanage/daycalendar";
    }

    @Autowired
    private DaymanageServices daymanageServices;

    @RequestMapping("mycalendarload")
    @ResponseBody
    public Object mycalendarload(@SessionAttribute("userId") Long userId) {
        return daymanageServices.aboutmeschedule(userId);
    }

    /**
     * 部门表 和职务表是数据
     *
     * @param model
     */
    private void deptAndPos(Model model) {
        List<Position> positions = positionDao.findAll();
        List<Dept> depts = deptDao.findAll();
        model.addAttribute("poslist", positions);
        model.addAttribute("deptlist", depts);
    }

    /**
     * 公共表数据
     *
     * @param model
     */
    private void typeAndStatus(Model model) {
        List<SystemTypeList> aoaScheduleList = typeDao.findByTypeModel("aoa_schedule_list");
        List<SystemStatusList> systemStatusLists = statusDao.findByStatusModel("aoa_schedule_list");
        model.addAttribute("types", aoaScheduleList);
        model.addAttribute("statuses", systemStatusLists);
    }

}
